<template>
  <div class="app-container shopGoods">
    <el-row>
      <el-col>
        <el-form :model="query" inline size="small">
          <el-form-item label="选择门店">
            <el-select v-model="query.shopId" filterable placeholder="请选择门店" style="width: 200px;" clearable>
              <el-option v-for="item in shopOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单号">
            <el-input v-model="query.orderNo" placeholder="请输入订单号" clearable/>
          </el-form-item>
          <el-form-item label="采购时间">
            <el-date-picker v-model="dateList"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            size="small"
                            end-placeholder="结束时间"
                            value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="签收时间">
            <el-date-picker
              v-model="inDateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="{
              disabledDate: (date) => {
                return date.getTime() > new Date().getTime();
              }
            }"
            />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="query.status" clearable>
              <el-option :value="null" label="全部"></el-option>
              <el-option :value="0" label="待确认"></el-option>
              <el-option :value="1" label="待发货"></el-option>
              <el-option :value="2" label="待签收"></el-option>
              <el-option :value="3" label="已完成"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="对账状态">
            <el-select v-model="query.confirmStatus" placeholder="请选择" clearable size="small" style="width: 100px">
              <el-option :value="null" label="全部"></el-option>
              <el-option :value="0" label="未对账"></el-option>
              <el-option :value="1" label="已对账"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button type="default" @click="reset">重置</el-button>
            <el-button type="warning" size="small" :loading="exportLoading" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col>
        <el-table :data="list" v-loading="loading" stripe :cell-style="{padding:'5px'}" show-summary :summary-method="summaryMethod">
          <el-table-column label="订单编号"  align="center" prop="orderNo" />
          <el-table-column label="所属门店"  align="center" prop="shopName" />
          <el-table-column label="采购总额"  align="center" prop="totalMoney" />
          <el-table-column label="实际收货总额" prop="actualTotalMoney" align="center"/>
          <el-table-column label="状态"  align="center" prop="statusText">
            <template slot-scope="scope">
              <el-tag size="mini" :type="statusColor[scope.row.status]">{{scope.row.statusText}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="对账状态" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.confirmStatus == 0 ? 'warning': 'success'">
                {{scope.row.confirmStatus == 0 ? '未对账': '已对账'}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="采购时间"  align="center" prop="createTime" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.status < 3" @click="cancel(scope.row)">拒绝</el-button>
              <el-button type="text" @click="getDetail(scope.row.id)">查看</el-button>
              <el-button type="text"
                         v-if="scope.row.status == 3 && scope.row.confirmStatus == 0"
                         @click="confirmOrder(scope.row)">确认对账
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="query.pageNum"
          :limit.sync="query.pageSize"
          @pagination="getList"
        />
      </el-col>
      <detail v-model="showDetail" :id="id" @success="getList"></detail>
    </el-row>
  </div>
</template>

<script>
import {listShop, shopModule} from "@/api/shop";
import {orderCancel, orderList, orderConfirm, orderExport} from '@/api/order'
import detail from './components/orderDetail.vue'
import {mapGetters} from "vuex";

export default {
  name: "order",
  data() {
    return {
      statusColor: {
        0: 'warning',
        1: 'warning',
        2: '',
        3: 'success',
        4: 'info',
      },
      query: {
        status: null,
        pageNum: 1,
        pageSize: 20
      },
      shopOptions: [],
      dateList: [],
      inDateRange: [],
      list: [],
      total: 0,
      loading: false,
      showDetail: false,
      id: '',
      exportLoading: false
    }
  },
  computed: {
    ...mapGetters(['sysUserId'])
  },
  methods: {
    getShopList(){
      listShop({pageNum: 1, pageSize: 1000, showType: 0, isReal: 1}).then(res=>{
        this.shopOptions = res.data;
      })
    },
    search() {
      this.query.pageNum = 1;
      this.getList()
    },
    reset() {
      this.query = {
        pageNum: 1,
        pageSize: 20
      }
      this.getList()
    },
    getList() {
      this.query.sysUserId = this.sysUserId
      this.loading = true
      this.query.startCreateTime = ''
      this.query.endCreateTime = ''
      this.query.startInStockTime = ''
      this.query.endInStockTime = ''
      if (this.dateList && this.dateList.length > 0) {
        this.query.startCreateTime = this.dateList[0]
        this.query.endCreateTime = this.dateList[1]
      }
      if (this.inDateRange && this.inDateRange.length > 0) {
        this.query.startInStockTime = this.inDateRange[0]
        this.query.endInStockTime = this.inDateRange[1]
      }
      orderList(this.query).then(res => {
        this.list = res.rows
        this.total = res.total
      }).finally(() => {
        this.loading = false
      })
    },
    getDetail(id) {
      this.id = id
      this.showDetail = true
    },
    cancel(row) {
      this.$prompt('请输入拒绝原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因'
      }).then(({ value }) => {
        orderCancel({id: row.id, shopId: this.shopId, cancelRemark: value}).then(res => {
          if (res.code == 200) {
            this.$message.success('拒绝成功')
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    confirmOrder(row) {
      this.$confirm(`确认对单号为[${row.orderNo}]的采购单进行对账吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderConfirm(row.id).then(res => {
          if (res.code == 200) {
            this.$message.success('订单已确认')
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    summaryMethod(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (['totalMoney', 'actualTotalMoney'].indexOf(column.property) >= 0) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else {
            sums[index] = 'N/A'
          }
        }

      })
      return sums
    },
    handleExport() {
      const queryParams = this.query;
      this.$confirm('是否确认导出所有采购订单数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return orderExport(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).finally(() => {
        this.exportLoading = false;
      });
    },
  },
  created() {
    this.getShopList()
    this.getList()
  },
  components: {
    detail
  }
}
</script>

<style scoped>

</style>
